﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using DTO;
using BUS;
using PopupControl;
using ServiceSearch;
using System.Xml;
using System.IO;

namespace simpleGUI_QLQTPM
{
    public partial class Form_TimKiem : Form
    {
        #region Controls
        //private Popup viewPopup = null;
        //private ViewProviders viewProviders = null;
        #endregion

        #region Attributes
        private static EventWaitHandle _waitHandle = new AutoResetEvent(false);
        private static int ROWS_PER_PAGE = 11;

        public Form _parent = null;
        private string _strDichVu = String.Empty;
        private int _widthRate = 0;
        private int _heightRate = 0;
        private int _leftRate = 0;
        private int _topRate = 0;

        private string _oldKeyword = String.Empty;
        private bool _searchAvailable = true;
        private SearchEngine _se = null;
        private Thread _searchThread = null;
        private AutoComplete _ac = null;
        private List<DuLieuDTO> _lstDuLieuDTO = null;
        private int _pageIdx = 0;

        private List<DuLieuDTO> _lstDuLieuDTOFiltered = null;
        private bool _flagFocus = false;
        #endregion

        #region Constants
        private const int FILTER_INFO_DUONG = 0;
        private const int FILTER_INFO_PHUONG = 1;
        private const int FILTER_INFO_QUAN = 2;
        #endregion

        public Form_TimKiem(string strDichVu)
        {
            InitializeComponent();
            this._strDichVu = strDichVu;
            this._searchAvailable = true;

            //this.viewPopup = new Popup(this.viewProviders = new ViewProviders());
            //this.viewPopup.AutoClose = false;
            //this.viewPopup.ShowingAnimation = PopupAnimations.Slide | PopupAnimations.TopToBottom;
            //this.viewPopup.HidingAnimation = PopupAnimations.Slide | PopupAnimations.BottomToTop;
            //this.viewProviders.ProviderChanged += fireView_Event;
        }

        #region Interface
        private void LB_CapNhatDuLieu_MouseEnter(object sender, EventArgs e)
        {
            Panel_CapNhatDuLieu_MouseEnter(sender, e);
        }

        private void LB_CapNhatDuLieu_MouseLeave(object sender, EventArgs e)
        {
            Panel_CapNhatDuLieu_MouseLeave(sender, e);
        }

        private void Panel_CapNhatDuLieu_MouseEnter(object sender, EventArgs e)
        {
            Panel_CapNhatDuLieu.BackgroundImage = simpleGUI_QLQTPM.Properties.Resources.staticbutton2_hover;
        }

        private void Panel_CapNhatDuLieu_MouseLeave(object sender, EventArgs e)
        {
            Panel_CapNhatDuLieu.BackgroundImage = simpleGUI_QLQTPM.Properties.Resources.staticbutton2;
        }

        private void PB_CapNhatDuLieu_MouseEnter(object sender, EventArgs e)
        {
            Panel_CapNhatDuLieu_MouseEnter(sender, e);
        }

        private void PB_CapNhatDuLieu_MouseLeave(object sender, EventArgs e)
        {
            Panel_CapNhatDuLieu_MouseLeave(sender, e);
        }

        private void Panel_TimKiem_MouseEnter(object sender, EventArgs e)
        {
            //Panel_TimKiem.BackgroundImage = simpleGUI_QLQTPM.Properties.Resources.staticbutton4_hover;
        }

        private void Panel_TimKiem_MouseLeave(object sender, EventArgs e)
        {
            //Panel_TimKiem.BackgroundImage = simpleGUI_QLQTPM.Properties.Resources.staticbutton4;
        }

        private void PB_TimKiem_MouseEnter(object sender, EventArgs e)
        {
            Panel_TimKiem_MouseEnter(sender, e);
        }

        private void PB_TimKiem_MouseLeave(object sender, EventArgs e)
        {
            Panel_TimKiem_MouseLeave(sender, e);
        }

        private void Button_Tim_MouseEnter(object sender, EventArgs e)
        {
            //Panel_Tim.BackgroundImage = simpleGUI_QLQTPM.Properties.Resources.staticbutton6_hover;
        }

        private void Button_Tim_MouseLeave(object sender, EventArgs e)
        {
            //Panel_Tim.BackgroundImage = simpleGUI_QLQTPM.Properties.Resources.staticbutton6;
        }

        private void Button_QuayLai_MouseEnter(object sender, EventArgs e)
        {
            //Panel_QuayLai.BackgroundImage = simpleGUI_QLQTPM.Properties.Resources.staticbutton6_hover;
        }

        private void Button_QuayLai_MouseLeave(object sender, EventArgs e)
        {
            // Panel_QuayLai.BackgroundImage = simpleGUI_QLQTPM.Properties.Resources.staticbutton6;
        }

        private void Button_GoogleMap_MouseEnter(object sender, EventArgs e)
        {
            ///Panel_GoogleMap.BackgroundImage = simpleGUI_QLQTPM.Properties.Resources.staticbutton6_hover;
        }

        private void Button_GoogleMap_MouseLeave(object sender, EventArgs e)
        {
            //Panel_GoogleMap.BackgroundImage = simpleGUI_QLQTPM.Properties.Resources.staticbutton6;
        }

        void Size_Rate(int width, int height, int left, int top)
        {
            _widthRate = (width * 10000) / 859;
            _heightRate = (height * 10000) / 727;
            _leftRate = (left * 10000) / 859;
            _topRate = (top * 10000) / 727;
        }

        void Resize_Control(Control TempControl)
        {
            TempControl.Width = (this.Width * _widthRate) / 10000;
            TempControl.Height = (this.Height * _heightRate) / 10000;
            TempControl.Left = (this.Width * _leftRate) / 10000;
            TempControl.Top = (this.Height * _topRate) / 10000;
        }

        private void Form_TimKiem_SizeChanged(object sender, EventArgs e)
        {
            //Size_Rate(479, 74, 292, 33); Resize_Control(PB_Noti_Text);
            //Size_Rate(48, 48, 239, 47); Resize_Control(PB_Noti_Icon);
            //Size_Rate(183, 35, 0, 125); Resize_Control(Panel_TimKiem);
            //Size_Rate(190, 91, 3, 128); Resize_Control(Panel_CapNhatDuLieu);
            //Size_Rate(600, 34, 200, 126); Resize_Control(PB_Title);
            //Size_Rate(603, 43, 199, 127); Resize_Control(PB_Input);
            //Size_Rate(587, 30, 207, 134); Resize_Control(TB_Input);
            //Size_Rate(134, 35, 660, 166); Resize_Control(Panel_Tim);
            //Size_Rate(449, 34, 205, 206); Resize_Control(PB_Combobox);
            //Size_Rate(433, 23, 212, 211); Resize_Control(CB_DichVu);
            //Size_Rate(107, 13, 209, 243); Resize_Control(LB_HTKQ);
            //Size_Rate(153, 15, 203, 168); Resize_Control(LB_HuongTK);
            //Size_Rate(119, 14, 638, 252); Resize_Control(LB_HinhThucHienThi);
            //Size_Rate(31, 24, 751, 248); Resize_Control(PB_Arrow);
            //Size_Rate(582, 219, 212, 286); Resize_Control(DGV_KetQua);
            //Size_Rate(177, 30, 9, 465); Resize_Control(LB_Status);
            //Size_Rate(145, 35, 204, 520); Resize_Control(Panel_GoogleMap);
            //Size_Rate(145, 35, 356, 520); Resize_Control(Panel_QuayLai);
            //Size_Rate(76, 74, 199, 44); Resize_Control(pbForum);
            //Size_Rate(93, 29, 275, 54); Resize_Control(lblForum);
            //Size_Rate(133, 28, 285, 85); Resize_Control(lblVaoDienDan);
            //Size_Rate(108, 25, 691, 168); Resize_Control(pbXoa);
            //Size_Rate(296, 16, 234, 141); Resize_Control(lblHuongDan);
            //Size_Rate(589, 102, 205, 167); Resize_Control(LB_Suggest);
            //Size_Rate(111, 21, 206, 194); Resize_Control(cbb_FilterDuong);
            //Size_Rate(111, 21, 323, 194); Resize_Control(cbb_FilterDichVu);
            //Size_Rate(604, 434, 199, 218); Resize_Control(PB_Datagrid);
            //Size_Rate(588, 417, 206, 225); Resize_Control(ffpResult);
            //Size_Rate(75, 17, 574, 656); Resize_Control(LB_Truoc);
            //Size_Rate(60, 17, 739, 655); Resize_Control(LB_Sau);
            //Size_Rate(26, 22, 663, 653); Resize_Control(TB_PageIndex);
            //Size_Rate(34, 14, 692, 656); Resize_Control(LB_Pages);
            //Size_Rate(31, 29, 151, 51); Resize_Control(PB_Noti_Icon);
        }
        #endregion

        private void Form_TimKiem_Load(object sender, EventArgs e)
        {
            // khoi tao Search Engine
            bool success = true;
            try
            {
                this._se = new SearchEngine();
                this._ac = new AutoComplete();
            }
            catch (System.Exception ex)
            {
                success = false;
                MessageBox.Show("Initialize failed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (!success)
            {
                try
                {
                    this.Close();
                }
                catch (System.Exception ex)
                {

                }
            }
            else
            {
                // nap du lieu vao combo box DichVu
                List<DichVuDTO> lstDichVuDTO = this._se.GetAllDichVuDTO();
                lstDichVuDTO.Sort(
                    delegate(DichVuDTO dv1, DichVuDTO dv2)
                    {
                        return dv1.TenDichVu.CompareTo(dv2.TenDichVu);
                    }
                );
                DichVuDTO dichVuDTO = new DichVuDTO();
                dichVuDTO.MaDichVu = 0;
                dichVuDTO.TenDichVu = "Tất cả dịch vụ";
                lstDichVuDTO.Insert(0, dichVuDTO);

                this.CB_DichVu.DataSource = lstDichVuDTO;
                this.CB_DichVu.ValueMember = "MaDichVu";
                this.CB_DichVu.DisplayMember = "TenDichVu";

                int idx = 0;
                for (idx = 0; idx < lstDichVuDTO.Count; idx++)
                {
                    if (this._strDichVu == lstDichVuDTO[idx].TenDichVu)
                        break;
                }

                if (idx >= lstDichVuDTO.Count)
                {
                    idx = 0;
                }

                this.CB_DichVu.SelectedIndex = idx;

                // them tooltip vao cac control
                ToolTip tt = new ToolTip();
                tt.SetToolTip(this.TB_Input, "Nơi nhập từ khóa tìm kiếm. Ví dụ: ATM Nguyen Van Cu");
                tt.SetToolTip(this.CB_DichVu, "Chọn loại hình dịch vụ cần tìm");

                // an paging control
                this.LB_Truoc.Visible = false;
                this.LB_Sau.Visible = false;
                this.TB_PageIndex.Visible = false;
                this.LB_Pages.Visible = false;

                //Thừa dòng này....................................................................................................................
                //this.xuatKQNgay();
            }
        }

        private void xuatKQNgay()
        {
            try
            {
                if (null != this._searchThread)
                {
                    if (this._searchThread.ThreadState == ThreadState.Running)
                    {
                        try
                        {
                            this._searchThread.Abort();
                        }
                        catch (System.Exception ex)
                        {

                        }

                        Thread.Sleep(100);
                    }
                }

                string strInput = "";
                int maDichVu = (int)this.CB_DichVu.SelectedValue;
                SearchInputObject si = new SearchInputObject(strInput, maDichVu);
                this._searchThread = new Thread(new ParameterizedThreadStart(this.SearchThread));
                this._searchThread.Start(si);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Panel_TimKiem_Click(object sender, EventArgs e)
        {
            this._parent.Location = this.Location;
            this._parent.Visible = true;
            this.Dispose();
        }

        private void PB_QuayLai_Click(object sender, EventArgs e)
        {
            Panel_TimKiem_Click(sender, e);
        }

        private void Sleep(int p)
        {
            throw new NotImplementedException();
        }

        private void SearchThread(object objInput)
        {
            this._searchAvailable = false;

            try
            {
                Thread searchThread = new Thread(new ParameterizedThreadStart(this.SearchingThread));
                searchThread.Start(objInput);
                //Form_ThongBao frm = new Form_ThongBao();
                //this.Invoke((MethodInvoker)delegate
                //{
                //    frm.Show();
                //});

            //    _waitHandle.WaitOne();

                //this.Invoke((MethodInvoker)delegate
                //{
                //    frm.Close();
                //});
            }
            catch (System.Exception ex)
            {
                Utilities.WriteLog(ex.Message);
            }
            finally
            {
                this._searchAvailable = true;
            }
        }

        private void SearchingThread(object objInput)
        {
            try
            {
                SearchInputObject si = (SearchInputObject)objInput;
                
                string strInput = si.InputString;
                int maDichVu = si.MaDichVu;

                this._pageIdx = 0;
                this.Invoke((MethodInvoker)delegate
                {
                    this.ffpResult.Controls.Clear();
                });

                this._lstDuLieuDTO = this._se.Search(strInput, maDichVu);
                this._lstDuLieuDTOFiltered = this._lstDuLieuDTO;
                if (this._lstDuLieuDTO.Count > 0)
                {
                    List<string> lstDuong = this._se.GetFilterInfo(this._lstDuLieuDTO, SearchEngine.FILTER_INFO_DUONG);
                    List<string> lstDichVu = this._se.GetFilterInfo(this._lstDuLieuDTO, SearchEngine.FILTER_INFO_DICHVU);
                    List<string> lstQuan = this._se.GetFilterInfo(this._lstDuLieuDTO, FILTER_INFO_QUAN);
                    ShowPage(this._pageIdx);

                    this.Invoke((MethodInvoker)delegate
                    {
                        cbb_FilterDuong.SelectedIndexChanged -= new EventHandler(cbb_FilterDuong_SelectedIndexChanged);
                        cbb_FilterDichVu.SelectedIndexChanged -= new EventHandler(cbb_FilterDichVu_SelectedIndexChanged);

                        cbb_FilterDuong.DataSource = lstDuong;
                        cbb_FilterDichVu.DataSource = lstDichVu;

                        cbb_FilterDuong.SelectedIndexChanged += new EventHandler(cbb_FilterDuong_SelectedIndexChanged);
                        cbb_FilterDichVu.SelectedIndexChanged += new EventHandler(cbb_FilterDichVu_SelectedIndexChanged);


                        this.LB_HuongTK.Text = "Có " + this._lstDuLieuDTO.Count.ToString() + " địa điểm thỏa yêu cầu";
                        this.TB_PageIndex.Visible = true;
                        this.LB_Pages.Visible = true;                        
                    });
                }
                else
                {

                    this.Invoke((MethodInvoker)delegate
                    {
                        this.LB_HuongTK.Text = "Hiện chúng tôi chưa có thông tin bạn muốn tìm";
                    });
                }
            }
            catch (System.Exception ex)
            {
                Utilities.WriteLog(ex.Message);
            }
            finally
            {
                _waitHandle.Set();
            }
        }

        public void PrepareDetailedResult(List<DuLieuThoDTO> lstDuLieuThoDTO)
        {
            if (null != this._lstDuLieuDTO)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    this.ffpResult.Controls.Clear();
                });

                for (int i = 0; i < lstDuLieuThoDTO.Count; i++)
                {
                    DuLieuThoDTO duLieuThoDTO = lstDuLieuThoDTO[i];

                    MyUC myUC = new MyUC(
                        duLieuThoDTO.TenDiaDiem,
                        duLieuThoDTO.SoNha + " " + duLieuThoDTO.TenDuong + ", P. " + duLieuThoDTO.TenPhuong + ", Q. " + duLieuThoDTO.TenQuanHuyen + ", " + duLieuThoDTO.TenTinhThanh,
                        duLieuThoDTO.TenDichVu,
                        duLieuThoDTO.ChuThich, duLieuThoDTO.KinhDo, duLieuThoDTO.ViDo);
                    this.Invoke((MethodInvoker)delegate
                    {
                        ffpResult.Controls.Add(myUC);
                    });
                }
            }
        }

        private void CB_DichVu_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DichVuDTO dichVuDTO = (DichVuDTO)this.CB_DichVu.SelectedItem;
                if (@"Tất cả dịch vụ" == dichVuDTO.TenDichVu)
                {
                    //this.LB_Status.Text = @"Tất cả";
                }
                else
                {
                    // this.LB_Status.Text = dichVuDTO.TenDichVu;
                }
            }
            catch (System.Exception ex)
            {
                Utilities.WriteLog(ex.Message);
            }
        }

        private void ShowPagingControl(int start, int end)
        {
            this.Invoke((MethodInvoker)delegate
            {                
                if (0 == start)
                {
                    this.LB_Truoc.Visible = false;
                }
                else
                {
                    this.LB_Truoc.Visible = true;
                }

                if (end >= this._lstDuLieuDTOFiltered.Count)
                {
                    this.LB_Sau.Visible = false;
                }
                else
                {
                    this.LB_Sau.Visible = true;
                }
            });
        }

        private void ShowPage(int pageIdx)
        {
            int start = pageIdx * ROWS_PER_PAGE;
            int end = (pageIdx + 1) * ROWS_PER_PAGE;

            this.Invoke((MethodInvoker)delegate
            {
                this.TB_PageIndex.Text = (pageIdx + 1).ToString();
                this.LB_Pages.Text = "/ " + ((int)(this._lstDuLieuDTOFiltered.Count / ROWS_PER_PAGE) + 1).ToString();
            });

            this.ShowPagingControl(start, end);
            List<DuLieuThoDTO> lstDuLieuThoDTO = this._se.Reference(this._lstDuLieuDTOFiltered, start, end);
            this.PrepareDetailedResult(lstDuLieuThoDTO);
        }

        private void LB_Truoc_Click(object sender, EventArgs e)
        {
            this.LB_Suggest.Visible = false;
            this._pageIdx--;
            this.ShowPage(this._pageIdx);
        }

        private void LB_Sau_Click(object sender, EventArgs e)
        {
            this.LB_Suggest.Visible = false;
            this._pageIdx++;
            this.ShowPage(this._pageIdx);
        }

        private void listBox2_MouseClick(object sender, MouseEventArgs e)
        {
            LB_Suggest.Visible = false;
        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                TB_Input.Text = LB_Suggest.SelectedItem.ToString();
            }
            catch (Exception ex)
            {

            }
        }

        private void TSMI_Thoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void TSMI_HuongDan_Click(object sender, EventArgs e)
        {
            Form_Help form = new Form_Help();
            form._parent = this;
            form.ShowDialog();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            string _currentKeyword = this.TB_Input.Text.Trim();
            if (_currentKeyword != this._oldKeyword)
            {
                if (_searchAvailable)
                {
                    try
                    {
                        if (null != this._searchThread)
                        {
                            if (this._searchThread.ThreadState == ThreadState.Running)
                            {
                                try
                                {
                                    this._searchThread.Abort();
                                }
                                catch (System.Exception ex)
                                {

                                }

                                //Thread.Sleep(100);
                            }
                        }

                        string strInput = this.TB_Input.Text;
                        int maDichVu = (int)this.CB_DichVu.SelectedValue;

                        SearchInputObject si = new SearchInputObject(strInput, maDichVu);
                        this._searchThread = new Thread(new ParameterizedThreadStart(this.SearchThread));
                        this._searchThread.Start(si);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    this._oldKeyword = _currentKeyword;
                }
            }
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            Form_Help form = new Form_Help();
            form._parent = this;
            form.ShowDialog();
        }

        private void cbb_FilterDuong_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbb_FilterDuong.SelectedItem != null)
                if (cbb_FilterDichVu.SelectedItem != null)
                    {
                        Filter(cbb_FilterDuong.SelectedItem.ToString(), cbb_FilterDichVu.SelectedItem.ToString(), this._lstDuLieuDTO);
                    }
        }

        private void cbb_FilterDichVu_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbb_FilterDuong.SelectedItem != null)
                if (cbb_FilterDichVu.SelectedItem != null)
                {
                    Filter(cbb_FilterDuong.SelectedItem.ToString(), cbb_FilterDichVu.SelectedItem.ToString(), this._lstDuLieuDTO);
                }
        }

        private void Filter(string tenDuong, string tenDichVu, List<DuLieuDTO> lstDuLieuDTO)
        {
            this._lstDuLieuDTOFiltered = this._se.GetFilteredData(tenDuong, tenDichVu, lstDuLieuDTO);
            this._pageIdx = 0;
            ShowPage(this._pageIdx);
            this.LB_HuongTK.Text = "Có " + this._lstDuLieuDTOFiltered.Count.ToString() + " địa điểm thỏa yêu cầu";
        }

		private void btn_DinhVi_Click(object sender, EventArgs e)
		{
			 using(GetLocation form = new GetLocation())
			 {
				 form.ShowDialog();
			 }
		}

        private void TB_Input_TextChanged(object sender, EventArgs e)
        {
            bool flag = false;
            string strInput = Utilities.FormatInputData(this.TB_Input.Text);
            for (int i = 0; i < this.LB_Suggest.Items.Count; i++)
            {
                if (Utilities.FormatInputData((string)this.LB_Suggest.Items[i]).Contains(strInput))
                {
                    flag = true;
                    break;
                }
            }

            if (!flag)
            {
                List<string> lstSuggest = this._ac.Suggest(this.TB_Input.Text);
                this.ShowSuggest(lstSuggest);
            }
            else
            {
                if (this.LB_Suggest.Items.Count > 0)
                {
                    this.LB_Suggest.Visible = true;
                }
            }
            if (((TextBox)sender).Text == "")
            {
                this.lblHuongDan.Visible = true;
            }
            else 
            {
                this.lblHuongDan.Visible = false;
            }
        }

        private void ShowSuggest(List<string> lstSuggest)
        {
            if (lstSuggest.Count > 0)
            {
                this.LB_Suggest.Visible = true;
            }
            else
            {
                this.LB_Suggest.Visible = false;
            }
            
            this.LB_Suggest.Items.Clear();
            for (int i = 0; i < lstSuggest.Count; i++)
            {
                this.LB_Suggest.Items.Add(lstSuggest[i]);
            }
        }

        private void TB_Input_Leave(object sender, EventArgs e)
        {
            if (!_flagFocus)
            {
                this.LB_Suggest.Visible = false;
            }
            if(null ==  this.TB_Input.Text || "" ==  this.TB_Input.Text )
                this.lblHuongDan.Visible = true;
        }

        private void Form_TimKiem_MouseDown(object sender, MouseEventArgs e)
        {
            this.LB_Suggest.Visible = false;
        }

        private void ffpResult_MouseDown(object sender, MouseEventArgs e)
        {
            this.LB_Suggest.Visible = false;
        }

        private void TB_Input_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                if (this.LB_Suggest.Visible)
                {
                    this._flagFocus = true;
                    this.LB_Suggest.Focus();
                    this.LB_Suggest.SelectedIndex = 0;
                    this._flagFocus = false;
                }
            }
            else if (e.KeyCode == Keys.Enter)
            {
                this.pbtim_Click(null, null);
            }
        }

        private void TB_PageIndex_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.TB_Input.Focus();
                int idx = 0;
                try
                {
                    idx = Int32.Parse(this.TB_PageIndex.Text);
                }
                catch (System.Exception ex)
                {
                    idx = 1;
                }

                if (idx < 1)
                {
                    idx = 1;
                }
                else if (idx > ((int)(this._lstDuLieuDTOFiltered.Count / ROWS_PER_PAGE) + 1))
                {
                    idx = (int)(this._lstDuLieuDTOFiltered.Count / ROWS_PER_PAGE) + 1;
                }
                this.ShowPage(idx - 1);
            }
        }

        private void TB_PageIndex_Click(object sender, EventArgs e)
        {
            this.TB_PageIndex.SelectAll();
        }

        private void TB_PageIndex_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.TB_Input.Text = "";
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            this.TB_Input.Text = "";
        }

        private void pictureBox2_MouseEnter(object sender, EventArgs e)
        {
            ((PictureBox)sender).BackgroundImage = global::simpleGUI_QLQTPM.Properties.Resources.BtnXoahover;
        }

        private void pictureBox2_MouseLeave(object sender, EventArgs e)
        {
            ((PictureBox)sender).BackgroundImage = global::simpleGUI_QLQTPM.Properties.Resources.btnXoa;
        }

        private void pictureBox3_Click(object sender, EventArgs e)
        {
            using (GetLocation form = new GetLocation())
            {
                form.ShowDialog();
            }
        }

        private void pictureBox3_MouseEnter(object sender, EventArgs e)
        {
            ((PictureBox)sender).BackgroundImage = global::simpleGUI_QLQTPM.Properties.Resources.dinhvi_hover;
        }

        private void pictureBox3_MouseLeave(object sender, EventArgs e)
        {
            ((PictureBox)sender).BackgroundImage = global::simpleGUI_QLQTPM.Properties.Resources.dinhvi;
        }

        private void label3_MouseEnter(object sender, EventArgs e)
        {
            ((Label)sender).ForeColor = Color.WhiteSmoke;
        }

        private void label3_MouseLeave(object sender, EventArgs e)
        {
            ((Label)sender).ForeColor = Color.Yellow;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {
            if (!File.Exists("config.xml"))
            {
                //MessageBox.Show("Bạn chưa cấu hình đường dẫn tới thư mục bản đồ trong tập tin config.ini. Vui lòng xem hướng dẫn.");
            }
            else
            {
                string strLink = "";
                try
                {
                    XmlDocument document = new XmlDocument();
                    document.Load("config.xml");

                    XmlElement root = document.DocumentElement;
                    XmlElement element = (XmlElement)root.SelectSingleNode("//LINK/FORUM");
                    strLink = element.InnerText;
                    System.Diagnostics.Process.Start("iexplore.exe",strLink);

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Không xác định được đường dẫn");
                }
            }
        }

        private void lblHuongDan_Click(object sender, EventArgs e)
        {
            this.lblHuongDan.Visible = false;
            this.TB_Input.Focus();
        }

        /// <summary>
        /// tao file config neu file bi xoa
        /// </summary>
        private void createConfig()
        {
            XmlTextWriter writer = new XmlTextWriter("config.xml", Encoding.UTF8);
            writer.WriteStartDocument();
            writer.WriteStartElement("CONFIG");
            writer.WriteString("\n");
            writer.WriteStartElement("HELP");
            writer.WriteStartElement("OPEN");
            writer.WriteString("true");
            writer.WriteEndElement();//end HELP
            writer.WriteEndElement();//end OPEN
            writer.WriteStartElement("MAP");
            writer.WriteStartElement("PATH");
            writer.WriteString("BanDo");
            writer.WriteEndElement();//end MAP
            writer.WriteEndElement();//end PATH
            writer.WriteEndElement();//end config
            writer.WriteEndDocument();

            writer.Flush();
            writer.Close();
        }

        /// <summary>
        /// read config xml file
        /// </summary>
        private void OpenConfigFile()
        {
            XmlDocument document = new XmlDocument();
            document.Load("config.xml");

            XmlElement root = document.DocumentElement;
            XmlElement element = (XmlElement)root.SelectSingleNode("//OPEN");

            string open = element.InnerText;
            if (open.Equals("true"))
            {
                Form_Help form = new Form_Help();
                form._parent = this;
                form.Show();
            }
        }

        /// <summary>
        /// Trang thai cua form khi mo chuong trinh
        /// </summary>
        private void XacDinhTrangThaiBanDau()
        {
            try
            {
                if (!File.Exists("config.xml"))
                {
                    createConfig();
                    OpenConfigFile();
                }
                else
                {
                    OpenConfigFile();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void Form_TimKiem_Shown(object sender, EventArgs e)
        {
            XacDinhTrangThaiBanDau();
        }

		private void giớiThiệuToolStripMenuItem1_Click(object sender, EventArgs e)
		{

		}

		private void giớiThiệuToolStripMenuItem1_Click_1(object sender, EventArgs e)
		{
			Form_GioiThieu form = new Form_GioiThieu();
			form.ShowDialog();
		}


        //Dư hàm này-------------------------------------------------------------------------------------------------------------------=============
        //private void btnTim_Click(object sender, EventArgs e)
        //{
            

        //    XuLyTim();
        //}

        private void TSMI_CapNhatDuLieu_Click(object sender, EventArgs e)
        {
            Form_CapNhatDuLieu frm = new Form_CapNhatDuLieu();
            frm.ShowDialog();
        }

        private void pbtim_Click(object sender, EventArgs e)
        {
            XuLyTim();
        }

        private void XuLyTim()
        {
            this.LB_Suggest.Visible = false;
            while (!this._searchAvailable)
            {
                //Thread.Sleep(1);
            }
            try
            {
                if (this.TB_Input.Text != this._oldKeyword)
                {
                    if (null != this._searchThread)
                    {
                        if (this._searchThread.ThreadState == ThreadState.Running)
                        {
                            try
                            {
                                this._searchThread.Abort();
                            }
                            catch (System.Exception ex)
                            {

                            }

                            //Thread.Sleep(100);
                        }
                    }

                    string strInput = this.TB_Input.Text;
                    int maDichVu = (int)this.CB_DichVu.SelectedValue;

                    SearchInputObject si = new SearchInputObject(strInput, maDichVu);
                    this._searchThread = new Thread(new ParameterizedThreadStart(this.SearchThread));
                    this._searchThread.Start(si);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LB_CapNhatDuLieu_Click(object sender, EventArgs e)
        {

        }
    }
}
